package kr.ac.mju.mdc.mjuapp.login;

import java.util.concurrent.atomic.AtomicInteger;

import kr.ac.mju.mdc.mjuapp.R;
import kr.ac.mju.mdc.mjuapp.cipher.CipherManager;
import kr.ac.mju.mdc.mjuapp.network.NetworkManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

/**
 * @author davidkim
 *
 */
public class LoginActivity extends Activity implements OnClickListener {
	public static final int LOGIN_SUCCESS = 0x11;
	public static final int LOGIN_FAIL = 0x12;
	public static final int NETWORK_FAIL = 0x13;
	public static final int GET_STD_NAME_SUCCESS = 0x14;
	public static final int GET_STD_NAME_FAIL = 0x15;

	private final int PROGRESS_DIALOG = 0x21;
	private final int LOGIN_FAIL_DIALOG = 0x22;

	public static final int LOGIN_TYPE_WEB = 0x31;
	public static final int LOGIN_TYPE_MOBILE = 0x32;
	public static final int LOGIN_TYPE_MYIWEB = 0x33;

	private AtomicInteger loadCount = new AtomicInteger();
	private final int LOAD_COUNT = 2;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			int what = msg.what;
			//
			switch (what) {
			case LOGIN_SUCCESS:
				if (loadCount.decrementAndGet() == LOAD_COUNT - 1)
					login(LOGIN_TYPE_WEB);
				else
					// getStdName
					getStdName();
				break;
			case LOGIN_FAIL:
				// dimiss Dialog
				dismissDialog(PROGRESS_DIALOG);
				showDialog(LOGIN_FAIL_DIALOG);
				((EditText) findViewById(R.id.login_passwd)).setText("");
				break;
			case NETWORK_FAIL:
				// dimiss Dialog
				dismissDialog(PROGRESS_DIALOG);
				// error weak signal msg
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_network_error_weak_signal),
						Toast.LENGTH_SHORT).show();
				break;
			case GET_STD_NAME_SUCCESS:
				// set pref
				setPreferences((String) msg.obj);
				// dimiss Dialog
				dismissDialog(PROGRESS_DIALOG);
				Toast.makeText(getApplicationContext(), "로그인 되었습니다", Toast.LENGTH_SHORT).show();
				setResult(RESULT_OK);
				// finish
				finish();
				break;
			case GET_STD_NAME_FAIL:
				// cookie remove
				CookieManager.getInstance().removeAllCookie();
				// dimiss Dialog
				dismissDialog(PROGRESS_DIALOG);
				Toast.makeText(getApplicationContext(), "학생정보를 불러올 수 없습니다 다시 로그인 하세요", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);
		// password Edittext
		((EditText) findViewById(R.id.login_passwd)).setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				// TODO Auto-generated method stub
				if (actionId == EditorInfo.IME_ACTION_DONE)
					((ImageButton) findViewById(R.id.login_login_btn)).performClick();
				return true;
			}
		});
		((ImageButton) findViewById(R.id.login_login_btn)).setOnClickListener(this);
		((TextView) findViewById(R.id.login_textview_autologin)).setOnClickListener(this);
		((TextView) findViewById(R.id.login_textview_save_user_id)).setOnClickListener(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// initLayout
		initLayout();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case PROGRESS_DIALOG:
			Dialog progressDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			progressDialog.setContentView(R.layout.loading_progress);
			progressDialog.setCancelable(false);
			return progressDialog;
		case LOGIN_FAIL_DIALOG:
			return new AlertDialog.Builder(this).setTitle("명지대학교").setMessage(getString(R.string.msg_login_fail)).setCancelable(true)
					.create();
		default:
			return null;
		}
	}

	/**
	 * 
	 */
	private void login(int type) {
		String id = ((EditText) findViewById(R.id.login_id)).getText().toString();
		String pw = ((EditText) findViewById(R.id.login_passwd)).getText().toString();
		LoginThread loginThread = new LoginThread(getApplicationContext(), handler, type, id, pw);
		loginThread.start();
	}

	/**
	 * 
	 */
	private void getStdName() {
		LoginStdNameThread stdNameThread = new LoginStdNameThread(getApplicationContext(), handler);
		stdNameThread.start();
	}

	/**
	 * @return
	 */
	private boolean checkIdPw() {
		String id = ((EditText) findViewById(R.id.login_id)).getText().toString();
		String passwd = ((EditText) findViewById(R.id.login_passwd)).getText().toString();
		if (id.equals("")) {
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_login_id_insufficient), Toast.LENGTH_SHORT)
					.show();
			((EditText) findViewById(R.id.login_id)).requestFocus();
			return false;
		} else if (passwd.equals("")) {
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_login_pw_insufficient), Toast.LENGTH_SHORT)
					.show();
			((EditText) findViewById(R.id.login_passwd)).requestFocus();
			return false;
		}
		return true;
	}

	/**
	 * @param login
	 */
	private boolean setPreferences(String stdName) {
		// get pref
		SharedPreferences pref = getSharedPreferences(getString(R.string.pref_name), MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();
		// get userId, checkAutoLogin, checkSaveUserId
		String userId = ((EditText) findViewById(R.id.login_id)).getText().toString();
		boolean checkAutoLogin = ((CheckBox) findViewById(R.id.login_chk_autologin)).isChecked();
		boolean checkSaveUserId = ((CheckBox) findViewById(R.id.login_chk_save_user_id)).isChecked();
		// set autoLogin
		if (checkAutoLogin) {
			editor.putString(getString(R.string.pref_key_user_id), userId);
			String userPw = ((EditText) findViewById(R.id.login_passwd)).getText().toString();
			userPw = CipherManager.encryptDES(userPw, getApplicationContext());
			if (userPw != null)
				editor.putString(getString(R.string.pref_key_user_pw), userPw);
			else {
				// Encryption failed.
				handler.sendEmptyMessage(LOGIN_FAIL);
				return false;
			}
		}
		// set saveUserId
		else if (checkSaveUserId)
			editor.putString(getString(R.string.pref_key_user_id), userId);
		// save autologin, saveuserid
		editor.putBoolean(getString(R.string.pref_key_auto_login), checkAutoLogin);
		editor.putBoolean(getString(R.string.pref_key_save_user_id), checkSaveUserId);
		// save stdName
		if (stdName != null)
			editor.putString(getString(R.string.pref_std_name), stdName);
		// commit
		editor.commit();
		return true;
	}

	/**
	 * 
	 */
	private void initLayout() {
		// get inputmanager
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		// get preference
		SharedPreferences pref = getSharedPreferences(getString(R.string.pref_name), MODE_PRIVATE);
		boolean checkSaveUserId = pref.getBoolean(getString(R.string.pref_key_save_user_id), false);
		EditText idEditText = ((EditText) findViewById(R.id.login_id));
		EditText pwEdittext = ((EditText) findViewById(R.id.login_passwd));
		// if set saving user_id
		if (checkSaveUserId) {
			String userId = pref.getString(getString(R.string.pref_key_user_id), null);
			idEditText.setText(userId);
			((CheckBox) findViewById(R.id.login_chk_save_user_id)).setChecked(checkSaveUserId);
			pwEdittext.requestFocus();
			imm.showSoftInput(pwEdittext, InputMethodManager.SHOW_FORCED);
		} else {
			idEditText.setText("");
			idEditText.requestFocus();
			imm.showSoftInput(idEditText, InputMethodManager.SHOW_FORCED);
		}
		pwEdittext.setText("");
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		switch (id) {
		case R.id.login_login_btn:
			// login
			if (NetworkManager.checkNetwork(LoginActivity.this)) {
				if (checkIdPw()) {
					showDialog(PROGRESS_DIALOG);
					loadCount.set(LOAD_COUNT);
					login(LOGIN_TYPE_MOBILE);
				}
			}
			break;
		case R.id.login_textview_autologin:
			((CheckBox) findViewById(R.id.login_chk_autologin)).performClick();
			break;
		case R.id.login_textview_save_user_id:
			((CheckBox) findViewById(R.id.login_chk_save_user_id)).performClick();
			break;
		}
	}
}
/* end of file */